package com.xianniu.ltc.common;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xianniu.ltc.model.vo.XnLeadVO;
import lombok.Data;
import org.springframework.web.bind.annotation.PathVariable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
@Data
public abstract class CleanObject<T> {

    private String id;
    private String text;

    public CleanObject(String id, String text){
        this.id = id;
        this.text = text;
    }

    public CleanObject(){
    }

    public JSONArray getObjects(@PathVariable String entity, JSONObject query, List<T> temList) {
        JSONArray temArray = new JSONArray();
        // 查询的字段
        JSONArray queryFields = query.getJSONArray("fields");
        List<String> keyList = queryFields.toJavaList(String.class);
        for(T poolVO : temList){
            JSONArray objectArray = new JSONArray();
            JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(poolVO));
            for(String key : keyList){
                String realKey = object.keySet().stream().filter(b -> key.equalsIgnoreCase(b)).findAny().orElse(null);
                if(StrUtil.isNotBlank(realKey)){
                    objectArray.add(Objects.isNull(object.get(realKey)) ? "" : object.get(realKey));
                }else{
                    objectArray.add("");
                }
            }
            JSONObject jiegou = new JSONObject();
            Class stuClass = poolVO.getClass();
            try {
                Method idMethod = stuClass.getDeclaredMethod("get" + id, null);
                Object idResult = idMethod.invoke(poolVO, null);
                Method textMethod = stuClass.getDeclaredMethod("get" + text, null);
                Object textResult = textMethod.invoke(poolVO, null);
                jiegou.put("id", idResult);
                jiegou.put("text", Objects.isNull(textResult) ? "" : textResult);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            jiegou.put("entity", entity);
            objectArray.add(jiegou);
            temArray.add(objectArray);
        }
        return temArray;
    }
}
